package com.last.service.impl;

import com.api.order.OrderClient;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.last.config.MyConfig;
import com.last.entity.Order;
import com.last.entity.Result;
import com.last.service.PayService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class PayServiceImpl implements PayService {

    @Resource
    private OrderClient orderClient;

    @Value("${notify_url}")
    private String notifyUrl;

    @Override
    public Result pay(String orderId) {
     try {
         //查询订单信息
         Order orderInfo = orderClient.findOrderInfo(orderId);

         //计算总金额
         Integer wallet = 0;
         Date orderInfoStartDate = orderInfo.getStartDate();

//         Integer time1 = Integer.valueOf(String.valueOf(orderInfoStartDate));
//         Date orderInfoLeaveDate = orderInfo.getLeaveDate();
//         Integer time2 = Integer.valueOf(String.valueOf(orderInfoLeaveDate));
         BigDecimal orderInfoOrderPrice = orderInfo.getOrderPrice();
         double dou = Double.parseDouble(String.valueOf(orderInfoOrderPrice));
//         Integer a = time2 - time1;
         int price = (int) ( dou);
         wallet += price;
         String payUrl = payOrder(orderId, wallet, notifyUrl);

         Map data = new HashMap();
         data.put("payUrl",payUrl);
         data.put("total_fee",wallet);
         data.put("orderId",orderId);

         return new Result(true,"下单成功",data);
     }catch (Exception e){
         return  new Result(false,"下单失败");
     }
    }

    private String payOrder(String orderId,Integer fee,String notifyUrl) throws  Exception{
        //1.构建配置
        MyConfig config = new MyConfig();
        //2.封装请求数据
        Map<String,String> requestParams = new HashMap<String, String>();
        requestParams.put("appid",config.getAppID());
        requestParams.put("mch_id",config.getMchID());
        requestParams.put("nonce_str", WXPayUtil.generateNonceStr());
        requestParams.put("body","民宿");
        requestParams.put("out_trade_no",orderId);//业务系统订单号
        requestParams.put("total_fee",fee+"");//订单金额，单位为分
        requestParams.put("spbill_create_ip","127.0.0.1");
        requestParams.put("notify_url",notifyUrl);
        requestParams.put("trade_type","NATIVE");//扫码支付

        //3.将map转xml串
        String reqeuestParamsXml = WXPayUtil.generateSignedXml(requestParams, config.getKey());

        //4.发请求
        WXPayRequest request = new WXPayRequest(config);
        String resultXml = request.requestWithoutCert("/pay/unifiedorder", UUID.randomUUID().toString(), reqeuestParamsXml, false);
        System.out.println(resultXml);

        //5.将resultXml转map集合
        final Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
        System.out.println(resultMap.get("code_url"));
        return resultMap.get("code_url");
    }

    @Override
    public String closeOrder(String orderId) throws Exception {
             MyConfig config=new MyConfig();
             Map<String,String> x=new HashMap<String, String>();
            x.put("appid",config.getAppID());
            x.put("mch_id",config.getMchID());
            x.put("out_trade_no",orderId );
            x.put("nonce_str",WXPayUtil.generateNonceStr());
             String r = WXPayUtil.generateSignedXml(x, config.getKey());
            WXPayRequest y = new WXPayRequest(config);
            String z = y.requestWithoutCert("/pay/close", UUID.randomUUID().toString(), r, false);
            System.out.println(z);
            final Map<String, String> resultMap = WXPayUtil.xmlToMap(z);
            return  resultMap.get("code_url");
    }
}
